package com.ruoyi.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.cat.domain.CatUserbasicTable;
import com.ruoyi.cat.service.ICatUserbasicTableService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.WxLoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.WxTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    private TokenService tokenService;
    private WxTokenService wxTokenService;

    @Autowired
    private ICatUserbasicTableService catUserService;

    @Override
    protected void initFilterBean() throws ServletException {
        ServletContext servletContext = this.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        if (ctx != null) {
            this.tokenService = ctx.getBean(TokenService.class);
            this.wxTokenService = ctx.getBean(WxTokenService.class);
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 确保服务已经注入
        if (tokenService == null || wxTokenService == null) {
            ServletContext servletContext = request.getServletContext();
            ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            if (ctx != null) {
                tokenService = ctx.getBean(TokenService.class);
                wxTokenService = ctx.getBean(WxTokenService.class);
            }
        }

        try {
            if (wxTokenService.getToken(request) == null) {
                handleAdminUser(request);
            } else {
                handleWxUser(request, response);
            }
            chain.doFilter(request, response);
        } catch (Exception e) {
            logger.error("Token验证失败", e);
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(401, "Token验证失败")));
            return;
        }
    }

    private void handleAdminUser(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
    }

    private void handleWxUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        WxLoginUser wxUser = wxTokenService.getWxUser(request);

        wxTokenService.verifyToken(wxUser);
        CatUserbasicTable catUserbasicTable = catUserService.selectCatUserbasicTableById(wxUser.getUserId());
        if (catUserbasicTable == null) {
            System.out.println("========== 当前用户已经不存在,请重新登录 =========== "+JSON.toJSONString(wxUser));
            String msg = "当前用户已经不存在,请重新登录";
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(401, msg)));
            return;
        }
        if (wxUser == null) {
            System.out.println("========== 登录过期了,请重新登录 =========== "+JSON.toJSONString(wxUser));
            String msg = "登录过期了,请重新登录";
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(401, msg)));
            return;
        }
        if (StringUtils.isNotNull(wxUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(wxUser, null, null);
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
    }
}
